/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helpdesk;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;

import java.sql.SQLException;

/**
 * Allow a user to view and modify their own profile. Parameters are only used
 * when a user is changing his/her profile. A profile change will be submitted
 * with a POST request.
 *
 * Parameters:
 * 1) email - required
 * 2) firstName - optional
 * 3) lastName - optional
 * 4) phoneNumber - optional
 * 5) address - optional
 * 6) zip - optional
 * 7) pass1 and pass2 - Presence of pass1 and pass2 will change password if they
 *    match.
 * 8) support - Change to/from a support user
 *
 * JSP attributes:
 * 1) user - All fields from above are sent as a User to the JSP page
 * 2) error - Error message. Can also contain a success message.
 *
 * Session variables:
 * 1) user
 *
 * @author brian
 */
public class ProfileServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        RequestDispatcher rd;
        HttpSession s;
        User user;
        String error = new String("");
        String phone;
        String zipcode = new String("");

        try {
            if ((user = HelpdeskUtil.authenticateUser(request, response)) != null)
            {
                if (request.getMethod().equals("POST"))
                {
                    User newUser=new User(user);
                    //TODO: validate some of these
                    newUser.setEmail(request.getParameter("email"));
                    newUser.setFirstName(request.getParameter("firstName").trim());
                    newUser.setLastName(request.getParameter("lastName").trim());
                    phone = request.getParameter("phoneNumber").trim();
                    if(phone == null){
                        phone = "";
                    }else{
                        for(int i = 0; i < phone.length(); i++) {
                            char c = phone.charAt(i);
                            if(!( ((c <= '9') && (c >= '0'))  || (c == '-'))){
                                phone = "";
                            }
                        }
                    }
                    newUser.setPhoneNumber(phone);
                    newUser.setAddress(request.getParameter("address").trim());
                    zipcode = request.getParameter("zip").trim();
                    if(zipcode == null){
                        zipcode = "nulls";
                    }else{
                        for(int i = 0; i < zipcode.length(); i++) {
                            char c = zipcode.charAt(i);
                            if(!(c <= '9' && c >= '0')){
                                zipcode = "";
                            }
                        }
                    }

                    newUser.setZip(zipcode);
                    //newUser.setZip(request.getParameter("zip".trim()));
                    String pass1 = request.getParameter("pass1");
                    String pass2 = request.getParameter("pass2");
                    if (request.getParameter("support") == null)
                        newUser.setSupport(false);
                    else
                        newUser.setSupport(true);
                    if (pass1.length() > 0 && pass1.equals(pass2))
                    {
                        newUser.setPassword(pass1);
                        error = "Password updated. ";
                    }
                    else if (pass1.length() > 0)
                        error = "Passwords do not match. ";

                    try
                    {
                        newUser.update();
                        s = request.getSession();
                        s.setAttribute("user", newUser);
                        error += "Profile updated.";
                    }
                    catch (SQLException ex)
                    {
                        error = "SQL exception: " + ex.getMessage();
                    }
                }

                request.setAttribute("error", error);
                rd = request.getRequestDispatcher("/WEB-INF/profile.jsp");
                rd.forward(request, response);
            }
        } finally {
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
